<?php

namespace App\Console\Commands;

use Exception;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class SerialNumberOrCreatedAtCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:serialCreated {table} {type}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Execute the console command
     * @throws Exception
     */
    public function handle(): void
    {
        $type = (int)$this->argument('type');
        $table = $this->argument('table');
        $hasColumn = match ($type) {
            0 => Schema::hasColumn($table, 'add_at'),
            1 => Schema::hasColumn($table, 'serial_number'),
            2 => Schema::hasColumn($table, 'updated_at'),
            default => false
        };

        if ($hasColumn) {
            $class = '\App\Library\Logic\\' . ucfirst(lineToHump($table)) . 'Logic';
            $model = new $class;
            $count = DB::table($table)->count();
            $ceil = ceil($count / 100);
            $i = 1;
            do {
                $idKey = $model->getFillable()[0];
                $list = $model::query()->limit(100)->offset(($i - 1) * 100)->get(['created_at', $idKey, 'updated_at']);
                foreach ($list as $v) {
                    if ($type === 1) $v->serial_number = date('YmdHis', $v->created_at) . random(6, 1);
                    else if ($type === 0) $v->add_at = date('Y-m-d H:i:s', $v->created_at);
                    else if ($type === 2) $v->new_at = ($v->updated_at > 0) ? date('Y-m-d H:i:s', $v->updated_at) : null;
                    $v->save();
                }
                $i++;
            } while ($i <= (int)$ceil);
        }
    }
}
